<?php
    class AdminDthink_NewsController extends Main_Controller_Action
    {
        public function init()
        {
            $this->loadTemplates('admin');
            $db = Zend_Registry::get('db');
        }
        
        public function preDispatch()
		{
			$auth = Zend_Auth::getInstance();
			if((!$auth->hasIdentity()) || ($auth->getIdentity()->level != 0))
			{
				if($this->_request->getActionName() != 'login')
				{
					$this->_redirect('/admin-dthink/index/login');
				}
			}
		}
        
        public function indexAction()
        {
            $this->view->headTitle('Quản lý tin tức');
            $news = new AdminDthink_Model_News();
            
            if($_POST['add'])
            {
                $this->_redirect('admin-dthink/news/create');
            }
            if($_POST['refresh'])
            {
                $this->_redirect('admin-dthink/news');
            }
            if($_POST['delete'])
            {
                $listId = $this->_request->getParam('check');
                $news->deleteManyNews($listId);
                $this->_redirect('admin-dthink/news');
            }
            
            $list = $news->listNews();
            $paginator = Zend_Paginator::factory($list);
            $paginator->setItemCountPerPage(20);
            $paginator->setPageRange(5);
            $currentPage = $this->_request->getParam('page', 1);
            $paginator->setCurrentPageNumber($currentPage);
            
            $this->view->data = $paginator;
            $this->view->total = count($list);
        }
        
        public function createAction()
        {
            $this->view->headTitle('Thêm tin mới');
            $news = new AdminDthink_Model_News();
            
            if($this->_request->isPost())
            {
                $filter = new Zend_Filter_StringTrim();
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                $news_image = $upload->getFileName('news_image', false);
                $cat_id = $this->_request->getParam('cat_id');
                $news_title = $filter->filter($this->_request->getParam('news_title'));
                $news_content = $filter->filter($this->_request->getParam('news_content'));
                $news_plaintext = $filter->filter($this->_request->getParam('news_plaintext'));
                $flag = true;
                
                $upload->addValidator('Size', false, 410000)
                       ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                if(!$upload->isValid())
				{
					$this->view->errorNewsImage = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
					$flag = false;
				}
                
                $validator = new AdminDthink_Form_ValidateNews();
                if($validator->validNewsTitle($news_title))
                {
                    $this->view->newsTitleValue = $news_title;
                }
                else
                {
                    $this->view->errorNewsTitle = 'Tiêu đề tin không được để trống và tối đa 300 kí tự';
                    $flag = false;
                }
                if($news->checkNews($news_title) > 0)
                {
                    $this->view->errorNewsTitle = 'Tiêu đề tin này đã tồn tại';
                    $flag = false;
                }
                if(!$validator->validNewsImage($news_image))
                {
                    $this->view->errorNewsImage = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
                    $flag = false;
                }
                if($validator->validNewsContent($news_content))
                {
                    $this->view->newsContentValue = $news_content;
                }
                else
                {
                    $this->view->errorNewsContent = 'Nội dung tin không được để trống';
                    $flag = false;
                }
                
                if($flag == true)
                {
                    preg_match('#\.([^\.]+)$#', $news_image, $matches);
					$fileExtension  = $matches[1];
					$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
					$options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName,'overwrite'=>true);
					$upload->addFilter('Rename',$options,'news_image');
					$upload->receive('news_image');
                    
                    $result = $news->addNews($cat_id, $news_title, $newFileName, $news_content, $news_plaintext);
                    $this->_redirect('admin-dthink/news');
                }
            }
        }
        
        public function editAction()
        {
            $this->view->headTitle('Sửa tin tức');
            $news_id = $this->_request->getParam('id');
            $news = new AdminDthink_Model_News();
            $this->view->data = $news->getNewsById($news_id);
            
            if($this->_request->isPost())
            {
                $filter = new Zend_Filter_StringTrim();
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                
                $news_image = $upload->getFileName('news_image', false);
                $cat_id = $this->_request->getParam('cat_id');
                $news_title = $filter->filter($this->_request->getParam('news_title'));
                $news_content = $filter->filter($this->_request->getParam('news_content'));
                $news_plaintext = $filter->filter($this->_request->getParam('news_plaintext'));
                $status = $this->_request->getParam('status');
                $flag = true;

                $validator = new AdminDthink_Form_ValidateNews();
                if(!$validator->validNewsTitle($news_title))
                {
                    $this->view->errorNewsTitle = 'Tiêu đề tin không được để trống và tối đa 300 kí tự';
                    $flag = false;
                }
                if($this->view->data['news_title'] != $news_title)
                {
                    if($news->checkNews($news_title, $news_id) > 0)
                    {
                        $this->view->errorNewsTitle = 'Tiêu đề tin này đã tồn tại';
                        $flag = false;
                    }
                }
                if(!$validator->validNewsContent($news_content))
                {
                    $this->view->errorNewsContent = 'Nội dung tin không được để trống';
                    $flag = false;
                }
                
                if($flag == true)
                {
                    if(!$validator->validNewsImage($news_image))
                    {
                        $result = $news->editNews($news_id, $cat_id, $news_title, '', $news_content, $news_plaintext, $status);
                        $this->_redirect('admin-dthink/news');
                    }
                    else
                    {
                        $upload->addValidator('Size', false, 410000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                        if(!$upload->isValid())
        				{
        					$this->view->errorNewsImage = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
        					$flag = false;
        				}
                        if($flag == true)
                        {
                            preg_match('#\.([^\.]+)$#', $news_image, $matches);
    						$fileExtension  = $matches[1];
    						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
    						
    						$options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName,'overwrite'=>true);
    						$upload->addFilter('Rename',$options,'news_image');
    						$upload->receive('news_image');
                            
                            $news->editNews($news_id, $cat_id, $news_title, $newFileName, $news_content, $news_plaintext, $status);
                            if (is_file(PUBLIC_PATH . '/files/news/' . $this->view->data['news_image']))
   							{
  								unlink(PUBLIC_PATH . '/files/news/' . $this->view->data['news_image']);
   							}
   							$this->_redirect('admin-dthink/news');
                        }
                    }
                }
            }
        }
        
        public function deleteAction()
        {
            $news_id = $this->_request->getParam('id');
            $news = new AdminDthink_Model_News();
            $news->deleteNews($news_id);
            $this->_redirect('admin-dthink/news');
        }
        
        public function searchAction()
        {
            $this->view->headTitle('Tìm kiếm tin');
            $news = new AdminDthink_Model_News();
            $filter = new Zend_Filter_StringTrim();
            $keyword = $filter->filter($this->_request->getParam('keyword'));
            $flag = true;
            
            if($this->_request->isPost())
            {
                $validation = new AdminDthink_Form_ValidateNews();
                if($validation->validNewsSearch($keyword))
				{
					$this->view->searchValue = $keyword;
				}
				else
				{
					$this->view->errorSearch = 'Bạn chưa nhập từ khóa';
					$result = $news->searchNews($keyword);
					$paginator = Zend_Paginator::factory($result);
					$paginator->setItemCountPerPage(20);
					$paginator->setPageRange(5);
					$currentPage = $this->_request->getParam('page', 1);
					$paginator->setCurrentPageNumber($currentPage);
						
					$this->view->total = count($result);
					$this->view->data = $paginator;
					$flag = false;
				}

				if($flag == true)
				{
					$result = $news->searchNews($keyword);
					$paginator = Zend_Paginator::factory($result);
					$paginator->setItemCountPerPage(20);
					$paginator->setPageRange(5);
					$currentPage = $this->_request->getParam('page', 1);
					$paginator->setCurrentPageNumber($currentPage);
						
					$this->view->total = count($result);
					$this->view->data = $paginator;
				}
            }
            
            if($_POST['add'])
            {
                $this->_redirect('admin-dthink/news/create');
            }
            if($_POST['refresh'])
            {
                $this->_redirect('admin-dthink/news');
            }
            if($_POST['delete'])
            {
                $listId = $this->_request->getParam('check');
                $news->deleteManyNews($listId);
                $this->_redirect('admin-dthink/news');
            }
            
            $validation = new AdminDthink_Form_ValidateNews();
            if($validation->validNewsSearch($keyword))
            {
                $this->view->searchValue = $keyword;
            }
            else
            {
                $this->view->errorSearch = 'Bạn chưa nhập từ khóa';
				$result = $news->searchNews($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(20);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
						
				$this->view->total = count($result);
				$this->view->data = $paginator;
				$flag = false;
            }
            
            if($flag == true)
            {
                $result = $news->searchNews($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(20);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
						
				$this->view->total = count($result);
				$this->view->data = $paginator;
            }
        }
    }
